#!/usr/bin/env python
"""
测试运行脚本
用于运行单元测试和集成测试
"""
import os
import sys
import subprocess
import argparse
import time

def run_command(command, cwd=None):
    """运行命令并打印输出"""
    print(f"\n执行命令: {command}")
    start_time = time.time()
    
    process = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
        cwd=cwd
    )
    
    # 实时打印输出
    for line in process.stdout:
        print(line, end="")
    
    process.wait()
    duration = time.time() - start_time
    
    print(f"\n命令执行完成，耗时: {duration:.2f}秒")
    print(f"退出代码: {process.returncode}")
    
    return process.returncode

def run_unit_tests(verbose=False):
    """运行单元测试"""
    print("\n===== 运行单元测试 =====")
    cmd = "pytest tests/ -v" if verbose else "pytest tests/"
    return run_command(cmd)

def run_integration_tests(verbose=False):
    """运行集成测试"""
    print("\n===== 运行集成测试 =====")
    cmd = "pytest tests/integration/ -v" if verbose else "pytest tests/integration/"
    return run_command(cmd)

def run_specific_test(test_path, verbose=False):
    """运行特定测试"""
    print(f"\n===== 运行特定测试: {test_path} =====")
    cmd = f"pytest {test_path} -v" if verbose else f"pytest {test_path}"
    return run_command(cmd)

def run_coverage(report_type="term"):
    """运行测试覆盖率"""
    print("\n===== 运行测试覆盖率 =====")
    cmd = f"pytest --cov=app tests/ --cov-report={report_type}"
    return run_command(cmd)

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="运行测试脚本")
    parser.add_argument("--unit", action="store_true", help="运行单元测试")
    parser.add_argument("--integration", action="store_true", help="运行集成测试")
    parser.add_argument("--all", action="store_true", help="运行所有测试")
    parser.add_argument("--test", type=str, help="运行特定测试文件或目录")
    parser.add_argument("--coverage", action="store_true", help="运行测试覆盖率")
    parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")
    
    args = parser.parse_args()
    
    # 如果没有指定任何选项，默认运行所有测试
    if not (args.unit or args.integration or args.all or args.test or args.coverage):
        args.all = True
    
    exit_code = 0
    
    if args.all or args.unit:
        unit_exit_code = run_unit_tests(args.verbose)
        exit_code = max(exit_code, unit_exit_code)
    
    if args.all or args.integration:
        integration_exit_code = run_integration_tests(args.verbose)
        exit_code = max(exit_code, integration_exit_code)
    
    if args.test:
        test_exit_code = run_specific_test(args.test, args.verbose)
        exit_code = max(exit_code, test_exit_code)
    
    if args.coverage:
        coverage_exit_code = run_coverage()
        exit_code = max(exit_code, coverage_exit_code)
    
    sys.exit(exit_code)

if __name__ == "__main__":
    main()
